package com.lordtan.commom.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

import org.apache.commons.lang.StringUtils;

/**
 * 用来获取服务器的ip，MAC地址等
 * @author lordtan
 * @date 2012-12-11
 */
public class IpUtils {
	
	/**
	 * 获取服务器ip地址
	 * @return
	 */
	public static String getIp(){
		InetAddress ia = null;
		try {
			ia = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		return ia.getHostAddress();
	}
	
	
	/**
	 * 获取服务器网卡物理地址
	 * 全球唯一的MAC地址
	 * @param host
	 * @return
	 */
	public static String getMAC()  
    {  
        String mac = "";  
        StringBuffer sb = new StringBuffer();  
        try   
        {  
        	InetAddress ia = InetAddress.getLocalHost();  
        	byte[] macs = NetworkInterface.getByInetAddress(ia).getHardwareAddress();   
            for(int i=0; i<macs.length; i++)  
            {  
                mac = Integer.toHexString(macs[i] & 0xFF);   
                  
                 if (mac.length() == 1)   
                 {   
                     mac = '0' + mac;   
                 }   
  
                sb.append(mac + "-");  
            }  
        } catch (SocketException e) {  
            e.printStackTrace();  
        } catch (UnknownHostException e) {  
            e.printStackTrace();  
        }  
          
        mac = sb.toString();  
        if(StringUtils.isEmpty(mac)){
        	return mac;
        }
        mac = mac.substring(0, mac.length()-1);  
        return mac;  
    }  
}
